package vip.bblog.cunadmin.modules.system.controller;


import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.bblog.cunadmin.annotation.group.Default;
import vip.bblog.cunadmin.annotation.group.Update;
import vip.bblog.cunadmin.common.entity.BaseResult;
import vip.bblog.cunadmin.common.entity.LoginUser;
import vip.bblog.cunadmin.common.entity.PageResult;
import vip.bblog.cunadmin.modules.system.dto.RoleAddDTO;
import vip.bblog.cunadmin.modules.system.dto.UserAddDTO;
import vip.bblog.cunadmin.modules.system.dto.UserEditPwdParams;
import vip.bblog.cunadmin.modules.system.dto.UserQueryParams;
import vip.bblog.cunadmin.modules.system.entity.SysLog;
import vip.bblog.cunadmin.modules.system.entity.SysUser;
import vip.bblog.cunadmin.modules.system.service.SysLogService;
import vip.bblog.cunadmin.modules.system.service.SysUserService;
import vip.bblog.cunadmin.modules.system.vo.SysUserVO;
import vip.bblog.cunadmin.util.UserUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统-用户 前端控制器
 * </p>
 *
 * @author yy
 * @since 2020-05-15
 */
@Api(tags = "web:系统用户管理")
@ApiSort(1)
@RestController
@RequestMapping("/system/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation(value = "添加用户")
    @PreAuthorize("hasAnyAuthority('sys:user:add')")
    @PostMapping
    public BaseResult<String> addUser(@Validated(Default.class) @RequestBody UserAddDTO user) {
        sysUserService.addUser(user);
        return BaseResult.success();
    }

    @ApiOperation(value = "修改密码")
    @PutMapping("editPwd")
    public BaseResult<SysUser> editPwd(@Validated(Update.class) @RequestBody UserEditPwdParams user) {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        SysUser sysUser = new SysUser();
        if(user.getId() == null){
            sysUser.setId(loginUser.getId());
        }else{
            sysUser.setId(user.getId());
        }
        if (StringUtils.isNotBlank(user.getPassword())) {
            sysUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        sysUserService.updateById(sysUser);
        return BaseResult.success();
    }

    @ApiOperation(value = "更新用户信息")
    @PreAuthorize("hasAnyAuthority('sys:user:update')")
    @PutMapping
    public BaseResult<UserAddDTO> updateUser(@Validated(Update.class) @RequestBody UserAddDTO user) {
        return BaseResult.success(sysUserService.updateUser(user));
    }

    @ApiOperation(value = "更新状态")
    @PreAuthorize("hasAnyAuthority('sys:user:enable')")
    @PutMapping("{userId}/status/{enable}")
    public BaseResult<RoleAddDTO> updateRole(@PathVariable Integer userId, @PathVariable Boolean enable) {
        sysUserService.updateRoleStatus(userId, enable);
        return BaseResult.success();
    }

    @ApiOperation(value = "刪除用户")
    @PreAuthorize("hasAnyAuthority('sys:user:del')")
    @DeleteMapping("{userId}")
    public BaseResult<RoleAddDTO> deleteUser(@PathVariable Integer userId) {
        sysUserService.delete(userId);
        return BaseResult.success();
    }

    @ApiOperation(value = "分页查询")
    @PreAuthorize("hasAnyAuthority('sys:user:list','sys:user:add','sys:user:update','sys:user:del','sys:user:enable')")
    @GetMapping
    public PageResult<List<SysUserVO>> listPage(UserQueryParams params) {
        return sysUserService.listPage(params);
    }

    @ApiOperation(value = "根据id查找")
    @PreAuthorize("hasAnyAuthority('sys:user:list','sys:user:add','sys:user:update','sys:user:del','sys:user:enable')")
    @GetMapping("{userId}")
    public BaseResult<UserAddDTO> selectById(@PathVariable Integer userId) {
        return sysUserService.selectById(userId);
    }

    @ApiOperation(value = "登录日志")
    @GetMapping("loginLog")
    public BaseResult<UserAddDTO> loginLog( HttpServletRequest request) {
        SysLog sysLog = new SysLog();
        LoginUser loginUser = UserUtils.getLoginUser();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        sysLog.setCtime(df.format(new Date()));// new Date()为获取当前系统时间
        sysLog.setContent("登录");
        sysLog.setUsername(loginUser.getUsername());
        sysLog.setHandleType(4);
        String ip = UserUtils.getIpAddr(request);
        loginUser.setLoginIp(ip);
        sysLog.setDescription(loginUser.toString());
        sysLogService.save(sysLog);
        return BaseResult.success();
    }

}

